/**
 * @description  持仓明细图（资产配置）
 * @author zht
 */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Spin, Tooltip, Radio, message } from 'antd';
import { PrimaryC, PrimaryGhostC } from '../../../comps/button';
import { SecondHeaderC, FirstHeaderC, TabC, TableC } from '../../../comps';
import upRed from '../../../assets/commom/up_arrow_red.png';
import downGreen from '../../../assets/commom/down_arrow_green.png';
import _ from 'lodash';
import myStyle from './index.less';
@Form.create()
class marketDetailed extends PureComponent {
  constructor() {
    super();
    this.state = {
      topN: 5, // 数量N
      columnsN_ZQZC: [], // 前N大-证券资产
      dataSourceN_ZQZC: [],
      columnsN_ZQFZ: [], // 前N大-证券负债
      dataSourceN_ZQFZ: [],
      columns_ZQZC: [], // 变动前N大-证券资产
      dataSource_ZQZC: [],
      columns_ZQFZ: [], // 变动前N大-证券负债
      dataSource_ZQFZ: [],
      currentPage: 1,
      numInPage: 1000,
      tabType: '1',
    };
  }

  componentDidMount() {
    const { args } = this.props;
    this.getData(args);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { args } = nextProps;

    if (JSON.stringify(args) !== JSON.stringify(this.props.args)) {
      this.getData(args);
    }
  }

  //获取数据
  getData = (args) => {
    const { currentPage, numInPage, topN } = this.state;
    const portfolioCode = args.portfolioCode
      ? {
          portfolioCode: args.portfolioCode,
        }
      : {
          portfolioCodeList: JSON.stringify([...args.portfolioCodeList]),
        };
    const datas = {
      ...portfolioCode,
      timeRange: args.timeRange,
      beginDate: args.beginDate,
      endDate: args.endDate,
      needPenetrate: args.needPenetrate,
      zqfz: args.zqfz,
    };
    this.props.dispatch({
      type: 'assetAllocationM/queryMarkeData',
      payload: {
        ...datas,
        topN: topN,
        currentPage: currentPage,
        numInPage: numInPage,
      },
      callback: (data) => {
        // biggest_zqzc/biggest_zqfz    change_zqzc/change_zqfz
        // 前N大-证券资产
        if (data && data.biggest_zqzc.dataSource.length && data.biggest_zqzc.columns.length) {
          const tempArr = data.biggest_zqzc.columns.filter((item) => item.key != 'holdAmount');
          const columnssN = this.changeColumnsN(tempArr);
          this.setState({
            columnsN_ZQZC: columnssN,
            dataSourceN_ZQZC: data.biggest_zqzc.dataSource,
          });
        } else {
          this.setState({
            columnsN_ZQZC: [],
            dataSourceN_ZQZC: [],
          });
        }
        // 前N大-证券负债
        if (data && data.biggest_zqfz.dataSource.length && data.biggest_zqfz.columns.length) {
          const tempArr = data.biggest_zqfz.columns.filter((item) => item.key != 'holdAmount');
          const columnssN = this.changeColumnsN(tempArr);
          this.setState({
            columnsN_ZQFZ: columnssN,
            dataSourceN_ZQFZ: data.biggest_zqfz.dataSource,
          });
        } else {
          this.setState({
            columnsN_ZQFZ: [],
            dataSourceN_ZQFZ: [],
          });
        }
        // 变动前N大-证券资产
        if (data && data.change_zqzc.dataSource.length && data.change_zqzc.columns.length) {
          const columnss = this.changeColumns(data.change_zqzc.columns);
          const dataSources = this.changeDataSource(data.change_zqzc.dataSource);
          this.setState({
            columns_ZQZC: columnss,
            dataSource_ZQZC: dataSources,
          });
        } else {
          this.setState({
            columns_ZQZC: [],
            dataSource_ZQZC: [],
          });
        }
        // 变动前N大-证券负债
        if (data && data.change_zqfz.dataSource.length && data.change_zqfz.columns.length) {
          const columnss = this.changeColumns(data.change_zqfz.columns);
          const dataSources = this.changeDataSource(data.change_zqfz.dataSource);
          this.setState({
            columns_ZQFZ: columnss,
            dataSource_ZQFZ: dataSources,
          });
        } else {
          this.setState({
            columns_ZQFZ: [],
            dataSource_ZQFZ: [],
          });
        }
      },
    });
  };

  //改变表格利率数据样式
  changRate = (data) => {
    if (data === null || data === undefined) {
      return '--';
    } else {
      if (isNaN(data)) {
        return data;
      } else {
        return (Number(data) * 100).toFixed(2) + '%';
      }
    }
  };

  //优化表格数据
  changeDataSource = (dataSource) => {
    const newDataSource = _.cloneDeep(dataSource);
    // newDataSource.forEach(value => {
    //     if (value.holdRatioFlag == 'up') {
    //         value.holdRatioChange = <div style={{ textAlign: 'right' }}> <span className={myStyle.cellUp}>{this.changRate(value.holdRatioChange)}</span><img style={{ width: "16px", height: '16px' }} src={upRed}></img></div>
    //     } else if (value.holdRatioFlag == 'down') {
    //         value.holdRatioChange = <div style={{ textAlign: 'right' }}> <span className={myStyle.cellDown}>{this.changRate(value.holdRatioChange)}</span> <img style={{ width: "16px", height: '16px' }} src={downGreen}></img></div>
    //     } else {
    //         value.holdRatioChange = <div style={{ textAlign: 'right' }}> <span className={myStyle.cell}>{this.changRate(value.holdRatioChange)} -</span></div>
    //     }
    // }
    // )
    return newDataSource;
  };

  //优化表格样式
  changeColumnsN = (columns) => {
    columns.forEach((value, index) => {
      if (value.key == 'holdRatio') {
        value['type'] = 'rate';
        if (this.props.args.portfolioCodeList?.length > 0) {
          value['width'] = '20%';
        }
      }
      // if (value.key == 'portfolioCode') {
      //   value['width'] = this.props.args.portfolioCode ? '25%' : '20%';
      // }
      if (value.key == 'securityName' || value.key == 'portfolioCode') {
        value.render = (text) => text || '';
      }
      if (value.key == 'tradingCode' ) {
        value['width'] = '20%';
      }
      //'交易属性
      if (value.key == 'TRDATTR') {
        let arr = [
          { value: 'B', title: '多头' },
          { value: 'PT', title: '普通' },
          { value: 'S', title: '空头' },
          { value: 'XY', title: '信用' },
          { value: 'ZRT', title: '转融通' },
          { value: 'ZS', title: '指数' },
        ];
        value.render = (text, record) => {
          let e = arr.filter((item) => {
            return item.value == text;
          });
          if (e && e.length > 0) {
            return e[0].title;
          } else {
            return '';
          }
        };
      }
      if(value.key!='securityName'&&value.key!='tradingCode'&& value.key!="portfolioCode"){
        value['width'] = 120;
      }
    });
    return columns;
  };

  changeColumns = (columns) => {
    columns.forEach((value, index) => {
      if (value.key == 'holdRatioChange') {
        value.align='right'
        // if (this.props.args.portfolioCodeList?.length > 0) {
        //   value['width'] = '20%';
        // }
        value.render = (text, row) => {
          if (row.holdRatioFlag == 'up') {
            return (
              <div style={{ textAlign: 'right' }}>
                {' '}
                <span className={myStyle.cellUp}>{this.changRate(text)}</span>
                <img style={{ width: '16px', height: '16px' }} src={upRed}></img>
              </div>
            );
          } else if (row.holdRatioFlag == 'down') {
            return (
              <div style={{ textAlign: 'right' }}>
                {' '}
                <span className={myStyle.cellDown}>{this.changRate(text)}</span> <img style={{ width: '16px', height: '16px' }} src={downGreen}></img>
              </div>
            );
          } else {
            return (
              <div style={{ textAlign: 'right' }}>
                {' '}
                <span className={myStyle.cell}>{this.changRate(text)} -</span>
              </div>
            );
          }
        };
      }
      if (value.key == 'securityName' || value.key == 'portfolioCode') {
        value.render = (text) => text || '';
      }
      if (value.key == 'tradingCode' ) {
        value['width'] = '20%';
      }
      //'交易属性
      if (value.key == 'TRDATTR') {
        let arr = [
          { value: 'B', title: '多头' },
          { value: 'PT', title: '普通' },
          { value: 'S', title: '空头' },
          { value: 'XY', title: '信用' },
          { value: 'ZRT', title: '转融通' },
          { value: 'ZS', title: '指数' },
        ];
        value.render = (text, record) => {
          let e = arr.filter((item) => {
            return item.value == text;
          });
          if (e && e.length > 0) {
            return e[0].title;
          } else {
            return '';
          }
        };
      }
      if(value.key!='securityName'&&value.key!='tradingCode'&& value.key!="portfolioCode"){
        value['width'] = 120;
      }
    });
    return columns;
  };

  //搜索
  searchData = () => {
    this.setState({}, this.getData(this.props.args));
  };

  //重置
  handleReset = () => {
    this.setState({
      topN: 5,
    });
  };

  //单选框点击时间
  onChange = (e) => {
    this.setState({
      topN: e.target.value,
    });
  };

  //搜索框
  showTitle = () => {
    return (
      <Form className={myStyle.titleStyle}>
        <Row justify='space-around'>
          <Col span={6}>
            <div className={myStyle.radio}>
              <span>数量N：</span>
              <Radio.Group onChange={this.onChange} value={this.state.topN}>
                <Radio value={5}>5</Radio>
                <Radio value={10}>10</Radio>
                <Radio value={20}>20</Radio>
              </Radio.Group>
            </div>
          </Col>
          <Col span={6}>
            <div style={{ width: (22 / 24) * 100 + '%', display: 'flex', flexDirection: 'row-reverse' }}>
              <Form.Item>
                <PrimaryC title='查询' onClick={this.searchData} />
                <PrimaryGhostC title='重置' style={{ marginLeft: '16px', borderRadius: '2px' }} onClick={this.handleReset} />
              </Form.Item>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  //
  tabItem = (type) => {
    const { columnsN_ZQZC, dataSourceN_ZQZC, columnsN_ZQFZ, dataSourceN_ZQFZ, columns_ZQZC, dataSource_ZQZC, columns_ZQFZ, dataSource_ZQFZ } = this.state;
    let columnsN, dataSourceN, columns, dataSource;
    if (type === '1') {
      columnsN = columnsN_ZQZC;
      dataSourceN = dataSourceN_ZQZC;
      columns = columns_ZQZC;
      dataSource = dataSource_ZQZC;
    } else {
      columnsN = columnsN_ZQFZ;
      dataSourceN = dataSourceN_ZQFZ;
      columns = columns_ZQFZ;
      dataSource = dataSource_ZQFZ;
    }
    return (
      <Spin spinning={this.props.loading == true}>
         <div className={this.props.type==1?myStyle.market1:myStyle.market2}>
                    <div>
                        <SecondHeaderC title='前N大重仓' />
                        <TableC
                            columns={columnsN}
                            dataSource={dataSourceN}
                            rowKey="id"
                            hidePage={true}
                            scroll={{ y: 366 }}
                        />
                    </div>
                    <div>
                        <SecondHeaderC title='较期初变动量最大的N个持仓' />
                        <TableC
                            columns={columns}
                            dataSource={dataSource}
                            rowKey="id"
                            hidePage={true}
                            scroll={{ y: 366 }}
                        />
                    </div>
                </div>
      </Spin>
    );
  };
  render() {
    return (
      <div>
        <FirstHeaderC
          title={
            <div>
              {' '}
              <span>持仓明细</span>
              <Tooltip title={<div>回购和现金不参与统计</div>}>
                <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
              </Tooltip>
            </div>
          }
        />
        {this.showTitle()}
        <div style={{ marginTop: '20px' }}>
          <TabC
            tabSource={[
              { title: '证券资产', key: '1', content: this.tabItem(this.state.tabType) },
              { title: '证券负债', key: '2', content: this.tabItem(this.state.tabType) },
            ]}
            activeKey={this.state.tabType}
            onChange={(key) => {
              this.setState({
                tabType: key,
              });
            }}
          />
        </div>
      </div>
    );
  }
}
export default connect(({ assetAllocationM, loading }) => ({
  assetAllocationM,
  loading: loading.effects['assetAllocationM/queryMarkeData'],
}))(marketDetailed);
